﻿using System.Collections.Generic;
using System.Text.RegularExpressions;
using System;

namespace FreeBroker
{
    class ComDirect : Provider
    {
        private static string site = "http://www.comdirect.de";
        private static string uri = site + "/inf/search/";

        public override string Search(string searchTerm)
        {
            string request = uri + "general.html?SEARCH_VALUE=" + searchTerm;
            //string searchQuery = "ad=&koop=&sCat=ALL&sSearchterm=" + searchTerm + "&x=5&y=11";
            string content = new Communication().GetSearchComdirect(request);
            return content;
        }

        /// <summary>
        ///     First retrieves response for URI, then parses the page.
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        public List<ComDirectSearchResult> ParseSearchResultsFromUri(string uri)
        {
            List<ComDirectSearchResult> results = new List<ComDirectSearchResult>();
            string content = new Communication().SendGetRequest(ComDirect.uri + uri);
            if (content != null && content.Length > 0)
            {
                results = ParseSearchResultsFromContent(content);
            }
            return results;
        }

        /// <summary>
        ///     Parses content of a page.
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public List<ComDirectSearchResult> ParseSearchResultsFromContent(string content)
        {
            List<ComDirectSearchResult> list = new List<ComDirectSearchResult>();
            if (content == null || content.Length == 0)
            {
                return list;
            }
            //
            // Check hits count
            string regexString = @"\[*?(\d+(\.\d+|))\sTreffer\]";
            Regex regex = new Regex(regexString, RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase);
            string hits = null;
            Match matchHits = regex.Match(content);
            if (matchHits != null)
            {
                hits = matchHits.Groups[1].Value;
            }
            Console.WriteLine("Hits: " + hits);
            //
            // Scan all search entries
            regexString = "<tr.+?<td.+?href=\"(.+?)\".+?title=\"(.+?)\".+?<td>.+?\\s+(.+?)\\s.+?<td>.+?\\s+(.+?)\\s.+?<td>.+?\\s+(.+?)\\s.+?<td>.+?\\s+(.+?)\\s.+?title=\"(.+?)\".+?</tr>";
            regex = new Regex(regexString, RegexOptions.Singleline | RegexOptions.IgnoreCase);
            MatchCollection col = regex.Matches(content);
            foreach (Match match in col)
            {
                ComDirectSearchResult result = new ComDirectSearchResult();
                result.Url = site + match.Groups[1].Value;
                result.Name = ClearString(match.Groups[2].Value);
                result.Type = InformerType.FromName(ClearString(match.Groups[3].Value));
                result.ActualValue = ClearString(match.Groups[4].Value);
                result.Currency = ClearString(match.Groups[5].Value);
                result.DateTime = ClearString(match.Groups[6].Value);
                result.StockMarket = ClearString(match.Groups[7].Value);
                list.Add(result);
            }
            // Check if there are more search results
            regexString = "/ccf/img/pager_next\\.gif";
            regex = new Regex(regexString);
            Match match2 = regex.Match(content);
            if (match2 != null)
            {
                string nextUrl = match2.Groups[1].Value;
                if (nextUrl.Length > 0)
                {
                    this.nextUrl = nextUrl;
                }
                else
                {
                    this.nextUrl = null;
                }
            }
            else
            {
                this.nextUrl = null;
            }
            return list;
        }

        private string ClearString(string input)
        {
            if (input == null || input.Length == 0)
            {
                return "--";
            }
            input = Helper.UnescapeHtmlString(input.Trim());
            return input;
        }

        public string nextUrl;

        /// <summary>
        ///     Parses content of the overview page.
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public ComDirectSearchResult ParseOverviewPage(string content)
        {
            if (content == null || content.Length == 0)
            {
                return null;
            }
            string regexString = "Gehen Sie zur.+?href=\"(.+?)\".+?\\<h1\\>\r\n(.+?)\r.+?fcRed\"\\>(.+?)\\</p\\>.+?\\<p\\>Typ:&nbsp;\\<b\\>(.+?)\\<.+?p\\>B&ouml;rse: (.+?)\\</p.+?Realtime-Kurs.+?\\>(.+?)\\<.+?Landesw&auml;hrung.+?\\<td\\>(.+?)\\<.+?Symbol.+?\\<td\\>(.+?)\\</td.+?WKN.+?\\<td\\>(.+?)\\</td.+?ISIN.+?\\<td\\>(.+?)\\</td";
            Regex regex = new Regex(regexString, RegexOptions.Singleline | RegexOptions.IgnoreCase);
            Match match = regex.Match(content);
            ComDirectSearchResult result = new ComDirectSearchResult();
            result.Url = site + match.Groups[1].Value;
            result.Name = match.Groups[2].Value;
            result.DateTime = match.Groups[3].Value.Replace("&nbsp;", " ");
            result.Type = InformerType.FromName(match.Groups[4].Value);
            result.StockMarket = match.Groups[5].Value;
            result.ActualValue = match.Groups[6].Value;
            result.Currency = match.Groups[7].Value;
            string symbol = match.Groups[8].Value;
            string wkn = match.Groups[9].Value;
            string isin = match.Groups[10].Value;
            return result;
        }
    }
}
